import { IFeidaoAiBrowserComponent } from '@feidao/web/interfaces';
import fire_component_msg from '@feidao/web/atom/browser/fsm/fire-component-msg';
import { generate } from '@feidao/core/querystring';
import { get } from '@feidao/web/request';
import client_login from '@feidao/web/atom/browser/msg/user-login';
import set_user from '@feidao/web/atom/browser/storage/put';

export default async function a003(fd: IFeidaoAiBrowserComponent, ...args: any[]) {
	const user_name = fd.data.node.querySelector('[data-feidao-id="user_name"]') as HTMLInputElement;
	if (!user_name.value) {
		fire_component_msg('zj-common-002', 'ec-001', 'fail', '请输入用户名');
		return;
	}
	const user_pwd = fd.data.node.querySelector('[data-feidao-id="user_pwd"]') as HTMLInputElement;
	if (!user_pwd.value) {
		fire_component_msg('zj-common-002', 'ec-001', 'fail', '请输入密码');
		return;
	}
	const pic_verification = fd.data.node.querySelector('[data-feidao-id="pic_verification"]') as HTMLInputElement;
	if (!pic_verification.value) {
		fire_component_msg('zj-common-002', 'ec-001', 'fail', '请输入验证码');
		return;
	}
	// 调用服务，验证，验证码输入的是否正确
	const param = { captcha: pic_verification.value };
	const vers = (await get('http://172.16.15.20/check_captcha', param)).responseText;
	// 验证码错误
	if (vers === 'false') {
		fire_component_msg('zj-common-002', 'ec-001', 'fail', '验证码错误');
		// 刷新验证码
		fd.fire('a003');
		return;
	}
	try {
		// 调用登录的通用服务
		const res = await client_login(fd.data.spaceid, user_name.value, user_pwd.value);
		await set_user(res, 'user');
		// 跳转到其他页面
		const backurl = fd.data.params.backurl;
		if (backurl) {
			window.location.href = backurl;
		} else {
			window.location.href = 'main.html';

		}
	} catch (error) {
		fire_component_msg('zj-common-002', 'ec-001', 'fail', error);
	}
}
